package com.zhuchaooasystem.ui.home.fragment.oa.record;

import android.media.MediaPlayer;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.holder.LocalRecordHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.entity.AudioInfo;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.LocalRecordContract;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.LocalRecordPresenter;
import com.zhuchaooasystem.utils.CalendarUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class LocalRecordActivity extends BaseActivity<LocalRecordPresenter> implements LocalRecordContract.View {

    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    //----
    @BindView(R.id.act_local_record_recycle)
    EasyRecyclerView recycle;
    @BindView(R.id.act_local_record_txt_desc)
    TextView txt_desc;

    //----加载中
    private ArrayList<String> uploadAudioList; //前一个界面传过来的需要上传的文件
    private List<String> recordList; //本地所有的文件
    private RecyclerArrayAdapter adapter;
    //----
    private List<AudioInfo> audioList; //选中的上传文件列表转换成录音类列表
    private MediaPlayer mediaPlayer;
    private int index;
    private boolean hasStop;
    //----
    private int cur_position;
    private List<Integer> checkPositionlist; //选中位置的列表


    @Override
    protected int getLayout() {
        return R.layout.activity_local_record;
    }

    @Override
    protected LocalRecordPresenter getPresenter() {
        return new LocalRecordPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getStringArrayListExtra("audioList")) {
            uploadAudioList = getIntent().getStringArrayListExtra("audioList");
        }
        //----
        cur_position = -1;
        //----
        checkPositionlist = new ArrayList<>();
        if (null == uploadAudioList) {
            uploadAudioList = new ArrayList<>();
        }
        //----
        initMediaPlayer();
    }

    private void initMediaPlayer() {
        //----
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                cur_position = -1;
                adapter.notifyDataSetChanged();
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                setDuration();
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                setDuration();
                return false;
            }
        });
    }

    private void setDuration() {
        if (hasStop) {
            if (null != uploadAudioList && uploadAudioList.size() > 0) {
                if (index != -1) {
                    audioList.add(new AudioInfo(uploadAudioList.get(index), CalendarUtils.duration2timeString(mediaPlayer.getDuration() / 1000)));
                }
                index++;
                if (index < uploadAudioList.size()) {
                    prepare();
                } else {
                    RxBus.get().post("localRecord", new BaseEvent<>(audioList));
                    finish();
                }
            } else {
                RxBus.get().post("localRecord", new BaseEvent<>(audioList));
                finish();
            }
        }
    }


    private void prepare() {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(uploadAudioList.get(index));
            mediaPlayer.prepare();
        } catch (Exception e) {
            if (hasStop) {
                if (null != uploadAudioList && uploadAudioList.size() > 0) {
                    audioList.add(new AudioInfo(uploadAudioList.get(index), "00:00"));
                    index++;
                    if (index < uploadAudioList.size()) {
                        prepare();
                    } else {
                        RxBus.get().post("localRecord", new BaseEvent<>(audioList));
                        finish();
                    }
                } else {
                    RxBus.get().post("localRecord", new BaseEvent<>(audioList));
                    finish();
                }
            }

        }
    }

    @Override
    protected void initView() {
        setActionBar();
        //----
        if (null != uploadAudioList && uploadAudioList.size() > 0) {
            txt_desc.setText("已选" + uploadAudioList.size() + "个录音文件");
        } else {
            txt_desc.setText("暂未选择录音文件");
        }
        //----
        recycle.setLayoutManager(new LinearLayoutManager(mContext));
        recycle.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<String>(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new LocalRecordHolder(parent, LocalRecordActivity.this);
            }
        });
    }

    private void setActionBar() {
        txt_title.setText(getString(R.string.actionbar_title_record_file));
        iv_back.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initDataAndLoadData() {
        //----
        mPresenter.getAudioPathFromSD();
    }


    @Override
    public void onClickPlay(int position) {
        try {
            if (cur_position == position) {
                if (mediaPlayer.isPlaying()) {
                    cur_position = -1;
                    adapter.notifyDataSetChanged();
                    mediaPlayer.stop();
                } else {
                    cur_position = position;
                    adapter.notifyDataSetChanged();
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(recordList.get(position));
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } else {
                cur_position = position;
                adapter.notifyDataSetChanged();
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.reset();
                mediaPlayer.setDataSource(recordList.get(position));
                mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IOException e) {
            ToastUtil.showShort(mContext, "该文件无法播放");
            cur_position = -1;
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
        }
    }

    @Override
    public void refreshData(List<String> recordList) {
        this.recordList = recordList;
        //选中的数据需要添加position到列表
        if (null != uploadAudioList && uploadAudioList.size() > 0 && null!=recordList && recordList.size()>0) {
            for (int i = 0; i < recordList.size(); i++) {
                for (int j = 0; j < uploadAudioList.size(); j++) {
                    if (recordList.get(i).equals(uploadAudioList.get(j))) {
                        checkPositionlist.add(i);
                    }
                }
            }
        }
        adapter.clear();
        adapter.addAll(recordList);
    }

    public void refreshView() {
        if (null != uploadAudioList && uploadAudioList.size() > 0) {
            txt_desc.setText("已选" + uploadAudioList.size() + "个录音文件");
        } else {
            txt_desc.setText("暂未选择录音文件");
        }
    }


    @OnClick({R.id.actionbar_iv_back, R.id.act_local_record_txt_add})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
            //添加
            case R.id.act_local_record_txt_add:
                index = -1;
                hasStop = true;
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                audioList = new ArrayList<>();
                if (null != uploadAudioList && uploadAudioList.size() > 0) {
                    setDuration();
                } else {
                    RxBus.get().post("localRecord", new BaseEvent<>(audioList));
                    finish();
                }
                break;
        }
    }

    public List<Integer> getCheckPositionlist() {
        return checkPositionlist;
    }

    public void setCheckPositionlist(List<Integer> checkPositionlist) {
        this.checkPositionlist = checkPositionlist;
    }

    public int getCur_position() {
        return cur_position;
    }

    public void setCur_position(int cur_position) {
        this.cur_position = cur_position;
    }

    public ArrayList<String> getUploadAudioList() {
        return uploadAudioList;
    }

    public void setUploadAudioList(ArrayList<String> uploadAudioList) {
        this.uploadAudioList = uploadAudioList;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            //释放资源
            mediaPlayer.release();
        }
    }
}
